<template>
  <el-dialog
          title="问卷二维码"
          width="600"
          :visible.sync="dialogVisible"
          @close="$emit('update:visible',false)">
    <div class="qrcodebody">
      <img :src="qrcodeSrc" alt="" class="qrcode">
      <div>
        <el-button size="small" @click="downloadIamge()" type="primary">下载二维码</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
  export default {
    name: 'previewImgDialog',
    props: ['visible', 'qrcodeSrc'],
    watch: {
      visible () {
        this.dialogVisible = this.visible
      }
    },
    data () {
      return {
        dialogVisible: this.visible
      }
    },
    created () {
    },
    methods: {
      downloadIamge () { // 下载图片地址和图片名
        let image = new Image()// 解决跨域 Canvas 污染问题
        image.setAttribute('crossOrigin', 'anonymous')
        image.onload = function () {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          let context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据

          let a = document.createElement('a') // 生成一个a元素
          let event = new MouseEvent('click') // 创建一个单击事件
          a.download = '问卷二维码' || 'photo' // 设置图片名称
          a.href = url // 将生成的URL设置为a.href属性
          a.dispatchEvent(event) // 触发a的单击事件
        }
        image.src = this.qrcodeSrc
      }
    }
  }
</script>
<style>
  .qrcodebody {
    display: flex;
    align-items: center;
  }

  .qrcode {
    width: 300px;
    height: 300px;
  }

  .previewlog {
    padding: 20px 0;
  }
</style>

